package com.wn.icloud.provider.cfg;


import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import com.wn.icloud.provider.client.DefaultStorageClient;
import com.wn.icloud.provider.client.DefaultTrackerClient;
import com.wn.icloud.provider.client.StorageClient;
import com.wn.icloud.provider.client.TrackerClient;
import com.wn.icloud.provider.conn.DefaultCommandExecutor;
import com.wn.icloud.provider.pool.ConnectionPool;
import com.wn.icloud.provider.pool.PooledConnectionFactory;

import java.util.HashSet;
import java.util.Set;

public class FastDfsConfig {

    private static ConnectionPool connectionPool;
    private static StorageClient storageClient;

    private static Configuration configuration;
    static{
        try {
            configuration = new PropertiesConfiguration("config.properties");
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化链接
     */
    public static StorageClient init() {
        PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(Integer.parseInt(configuration.getString("fdfs.soTimeout")),
                Integer.parseInt(configuration.getString("fdfs.connect-timeout")));
        GenericKeyedObjectPoolConfig conf = new GenericKeyedObjectPoolConfig();
        conf.setMaxTotal(Integer.parseInt(configuration.getString("fdfs.pool.max-total")));
        conf.setMaxTotalPerKey(Integer.parseInt(configuration.getString("fdfs.max-total-per-key")));
        conf.setMaxIdlePerKey(Integer.parseInt(configuration.getString("fdfs.max-idle-per-key")));
        connectionPool = new ConnectionPool(pooledConnectionFactory, conf);
        String string = configuration.getString("fdfs.tracker-list");
        String[] split = string.split(",");
        Set<String> trackerSet = new HashSet<String>();
        for (String str : split) {
            trackerSet.add(str);
        }
        trackerSet.add(configuration.getString("fdfs.tracker-list"));
        DefaultCommandExecutor commandExecutor = new DefaultCommandExecutor(trackerSet, connectionPool);
        TrackerClient trackerClient = new DefaultTrackerClient(commandExecutor);
        return new DefaultStorageClient(commandExecutor, trackerClient);
    }

    /**
     * 关闭链接
     */
    public static void close() {
        connectionPool.close();
    }

}
